from models.document import db
import datetime
import json

class DatabaseConnection(db.Model):
    """数据库连接配置"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    db_type = db.Column(db.String(20), nullable=False)  # mysql 或 postgresql
    host = db.Column(db.String(255), nullable=False)
    port = db.Column(db.Integer, nullable=False)
    username = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(255), nullable=False)
    database = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'db_type': self.db_type,
            'host': self.host,
            'port': self.port,
            'username': self.username,
            'database': self.database,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class SyncTask(db.Model):
    """同步任务配置"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    database_connection_id = db.Column(db.Integer, db.ForeignKey('database_connection.id'), nullable=False)
    sql_query = db.Column(db.Text, nullable=False)
    knowledge_id = db.Column(db.Integer, db.ForeignKey('knowledges.id'), nullable=False)
    document_fields = db.Column(db.Text, nullable=False)  # JSON string of fields to use as document
    metadata_fields = db.Column(db.Text, nullable=False)  # JSON string of fields to use as metadata
    embedding_fields = db.Column(db.Text, nullable=False)  # JSON string of fields to use for embedding
    last_run_at = db.Column(db.DateTime, nullable=True)
    status = db.Column(db.String(20), default='pending')  # pending, running, completed, failed
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    
    database_connection = db.relationship('DatabaseConnection', backref=db.backref('sync_tasks', lazy=True))
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'database_connection_id': self.database_connection_id,
            'sql_query': self.sql_query,
            'knowledge_id': self.knowledge_id,
            'document_fields': json.loads(self.document_fields),
            'metadata_fields': json.loads(self.metadata_fields),
            'embedding_fields': json.loads(self.embedding_fields),
            'last_run_at': self.last_run_at.isoformat() if self.last_run_at else None,
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class SyncTaskRun(db.Model):
    """同步任务运行记录"""
    id = db.Column(db.Integer, primary_key=True)
    sync_task_id = db.Column(db.Integer, db.ForeignKey('sync_task.id'), nullable=False)
    start_time = db.Column(db.DateTime, default=datetime.datetime.now)
    end_time = db.Column(db.DateTime, nullable=True)
    status = db.Column(db.String(20), default='running')  # running, completed, failed
    total_records = db.Column(db.Integer, default=0)
    processed_records = db.Column(db.Integer, default=0)
    error_message = db.Column(db.Text, nullable=True)
    
    sync_task = db.relationship('SyncTask', backref=db.backref('runs', lazy=True))
    
    def to_dict(self):
        return {
            'id': self.id,
            'sync_task_id': self.sync_task_id,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'status': self.status,
            'total_records': self.total_records,
            'processed_records': self.processed_records,
            'progress': round(self.processed_records / self.total_records * 100, 2) if self.total_records > 0 else 0,
            'error_message': self.error_message
        } 